package com.itany.ums.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Author：汤小洋
 * Date：2022-11-21 16:37
 * Description：<描述>
 */
public class MybatisUtil {
    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();

    static {
        factory = new SqlSessionFactoryBuilder().build(MybatisUtil.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
    }

    public static SqlSession getSession() {
        SqlSession session = local.get();
        if (session == null) {
            session = factory.openSession();
            local.set(session);
        }
        return session;
    }

    public static void close() {
        SqlSession session = local.get();
        if (session != null) {
            session.close();
            local.remove();
        }
    }

    public static void main(String[] args) {
        getSession();
    }
}